package cn.zsxmlv.modules.sys.ctrl;

import cn.zsxmlv.common.exception.RRException;
import cn.zsxmlv.common.utils.Constant;
import cn.zsxmlv.common.utils.PageUtils;
import cn.zsxmlv.common.utils.R;
import cn.zsxmlv.common.utils.RedisUtils;
import cn.zsxmlv.common.validator.ValidatorUtils;
import cn.zsxmlv.modules.sys.entity.SysUserEntity;
import cn.zsxmlv.modules.sys.redis.SysUserRedis;
import cn.zsxmlv.modules.sys.service.SysUserService;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.UUID;

/**
 * @author: zs
 * @description:
 * @date: 2019/2/10 16:19
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserCtrl extends BaseCtrl {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRedis sysUserRedis;

    @RequestMapping("/info")
    public R info() {
        return R.ok().put("user", getUser());
    }

    /**
     * 新增用户
     * @param user
     * @return
     */
    @RequestMapping("/save")
    public R save(@RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user);

        user.setCreateUserId(getUserId());
        sysUserService.save(user);
        return R.ok();
    }

    /**
     * 所有用户列表
     */
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        //只有超级管理员，才能查看所有管理员列表
        if(getUser().getCreateUserId() != Constant.SUPER_ADMIN){
            params.put("createUserId", getUserId());
        }
        PageUtils page = sysUserService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 更改用户状态
     * @param userId 用户ID
     * @param status 用户状态
     * @return
     */
    @RequestMapping("/changeStatus/{userId}/{status}")
    public R changeStatus(@PathVariable Integer userId, @PathVariable Integer status) {
        SysUserEntity entity = sysUserService.selectById(userId);
        entity.setStatus(status);
        sysUserService.updateById(entity);

        // 用户状态被禁用后将用户踢下线
        if (status == 1) {
            sysUserRedis.offline(userId);
        }

        return R.ok();
    }

}
